package com.imooc.order.controller;


import com.imooc.order.converter.OrderFrom2OrderDTO;
import com.imooc.order.dao.OrderMasterDao;
import com.imooc.order.dto.OrderDTO;
import com.imooc.order.enums.ResultEnum;
import com.imooc.order.exception.OrderException;
import com.imooc.order.from.Orderfrom;
import com.imooc.order.service.OrderService;
import com.imooc.order.utils.Utils;
import com.imooc.order.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;

    /**
     * 1.参数校验
     * 2。查询商品信息
     * 3。计算总价
     * 4。扣库存
     * 5。订单入库
     */

    @PostMapping("/create")
    public ResultVo<Map<String,String>> create(@Valid Orderfrom orderfrom, BindingResult bindingResult) throws OrderException {
        if (bindingResult.hasErrors()) {
            log.error("创建订单，参数异常  orderfrom={}", orderfrom);
            throw new OrderException(ResultEnum.Param_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        //orderFrom -> orderDTO
        OrderDTO orderDTO = OrderFrom2OrderDTO.conver(orderfrom);
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("创建订单，购物车信息为空");
            throw new OrderException(ResultEnum.CART_EMPTY);
        }
        OrderDTO result=orderService.create(orderDTO);
        Map<String, String> map = new HashMap<>();
        map.put("orderId", result.getOrderId());
        return Utils.success(map);
    }

}
